import { Crypt } from '../utils/CryptoJS'
import { _this } from '../main'

let baseURL = ''

if (process.env.NODE_ENV === 'development') {
  // baseURL = 'http://192.168.1.99:8079'
}

let ajaxList = []

function ajaxNext(token) {
  _this.$store.dispatch('app/on_token', token)
  ajaxList.forEach((ajax) => {
    ajax.Authorization = token
    ajaxSend(ajax)
  })
  ajaxList = []
}

function ajaxSend(obj) {
  uni.request({
    url: obj.url,
    method: obj.method,
    data: obj.data,
    timeout: 60000,
    header: {
      // Authorization: 'Bearer ' + obj.Authorization,
      tokens: obj.tokens,
      timestamp: obj.timestamp,
      param: localStorage.getItem('param') || '',
      sign: localStorage.getItem('sign') || '',
    },
    success(request) {
      if (request.data.code === 200) {
        if (obj.next) {
          ajaxNext(request.data.data.accessToken)
        }
        obj.success(request.data)
      } else if (request.data.code == 403) {
        // token 失效
        if (_this.$store.state.app.token) {
          _this.$store.dispatch('app/on_token', '')
          _this.$api.reGetWxCode('token')
        }
      } else {
        if (obj.next) {
          if (_this.$store.state.app.token) {
            _this.$store.dispatch('app/on_token', '')
            _this.$api.reGetWxCode('token')
          }
        } else {
          // if (request.data.msg) {
          //   showMsg(request.data.msg)
          // }
          obj.fail(request.data)
        }
      }
    },
    fail(error) {
      showMsg('网络环境异常')
      obj.fail(error)
    },
  })
}

function request(url, method = 'GET', token = '') {
  return (params, href = '') => {
    return new Promise((resolve, reject) => {
      const timestamp = new Date().getTime()
      const sig = 'yuze'
      const tokens = Crypt(sig + timestamp)

      // let Authorization = _this.$store.state.app.token
      let obj = {
        url: baseURL + url + href,
        method: method,
        data: params,
        tokens: tokens,
        timestamp: timestamp,
        success: resolve,
        fail: reject,
      }
      // if (!Authorization && !token) {
      //   ajaxList.push(obj)
      // } else {
      //   if (!Authorization && token === 'token') {
      //     obj.next = true
      //   }
      //   ajaxSend(obj)
      // }
      ajaxSend(obj)
    })
  }
}

export const http = {
  post: (url, token) => {
    return request(url, 'POST', token)
  },
  get: (url, token) => {
    return request(url, 'GET', token)
  },
}

function showMsg(msg) {
  uni.showToast({
    icon: 'none',
    title: msg || '服务加载中！',
    duration: 2000,
  })
}
